package top.huxy.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.huxy.boot.exception.NoCredentialsException;
import top.huxy.boot.exception.NoSupportOperationException;
import top.huxy.boot.exception.RequestAbortedException;
import top.huxy.boot.exception.RequestParamIllegalException;
import top.huxy.boot.util.ExceptionUtils;
import top.huxy.boot.util.obj.Result;

/**
 * @Classname ErrorAdvice
 * @Description ErrorAdvice
 * @Date 2021/8/31 11:50
 * @Created by huxy
 */
@Slf4j
@ControllerAdvice
public class ErrorAdvice {
    @ExceptionHandler({
            NoCredentialsException.class,
            RequestParamIllegalException.class,
            NoSupportOperationException.class,
            RequestAbortedException.class})
    @ResponseBody
    public Result exceptions(Exception e) {
        if (e == null) {
            return Result.serverError("内部错误");
        }

        //记录异常
        ExceptionUtils.logError(e);

        //自定义异常返回自定义的信息
        return Result.clientError(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        if (e == null) {
            log.error("内部错误，未知错误");
            return Result.serverError("内部错误，未知错误");
        }

        //记录异常
        ExceptionUtils.logError(e);

        //spring产生的异常，返回固定错误信息
        return Result.clientError("内部错误");
    }
}
